import React from 'react';
import CommentInput from './CommentInput';
import CommentList from './CommentList'
import wrapWithLoadData  from './wrapWithLoadData';


require('./Comment.css');

class CommentApp extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            comments:props.data|| []
        }
    }

    componentWillMount() {
        this._loadComments()
    }

    handleSubmitComment(comment) {
        if (!comment) return
        if (!comment.username) return alert('请输入用户名')
        if (!comment.content) return alert('请输入评论内容')
        const comments = this.state.comments

        comments.push(comment)
        this.setState({
            comments: this.state.comments

        })
        //this._saveComments(comments)
        this.props.saveData(comments)
    }

    _saveComments(comments) {
        localStorage.setItem('comments', JSON.stringify(comments))
    }
    _loadComments() {
        let comments = localStorage.getItem('comments')
        if (comments) {
            comments = JSON.parse(comments)
            this.setState({ comments: comments })
        }
    }
    handlerDeleteComment(index){
        const comments = this.state.comments
        if (comments) {
            comments.splice(index,1)
            this.setState({ comments: comments })
            //this._saveComments(comments)
            this.props.saveData(comments)
        }
    }


    render() {
        return (
            <div className='wrapper'>
                <CommentInput onSubmit={this.handleSubmitComment.bind(this)}></CommentInput>
                <CommentList comments={this.state.comments} onDeleteComment={this.handlerDeleteComment.bind(this)} />
            </div>
        )
    }
}

CommentApp=wrapWithLoadData (CommentApp,'comments')
export default CommentApp